package org.jeecg.modules.c.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.jeecg.modules.c.entity.DActiveAlarm;
import org.jeecg.modules.c.entity.DAlarmH;
import org.jeecg.modules.c.entity.MSignal;
import org.jeecg.modules.c.mapper.DAlarmHMapper;
import org.jeecg.modules.c.service.IDActiveAlarmService;
import org.jeecg.modules.c.service.IDAlarmHService;
import org.jeecg.modules.c.service.IMSignalService;
import org.jeecg.modules.concat.FocConcat;
import org.jeecg.modules.enmu.AttributeLength;
import org.jeecg.modules.enmu.MessageTypeEnum;
import org.jeecg.modules.foc.entity.FocAlarm;
import org.jeecg.modules.foc.entity.FocPointData;
import org.jeecg.modules.hand.LoginHandler;
import org.jeecg.modules.utils.SendMessageUtils;
import org.jeecg.modules.vo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 历史告警管理
 * @Author: jeecg-boot
 * @Date: 2024-11-05
 * @Version: V1.0
 */
@Service
@Slf4j
public class DAlarmHServiceImpl extends ServiceImpl<DAlarmHMapper, DAlarmH> implements IDAlarmHService {

    /**
     * 获取活动告警数据
     *
     * @return
     */
    @Autowired
    private DAlarmHMapper dAlarmHMapper;
    @Autowired
    private IMSignalService mSignalService;
    @Autowired
    private IDActiveAlarmService dActiveAlarmService;


    @Override
    public List<DActiveAlarm> getSendData() {
        return dAlarmHMapper.getSendData();

    }

    @Override
    public void onlineSaveAlarm(FocAlarm focAlarm) {


        //先根据GUID判断信号表中是否存在
        QueryWrapper<MSignal> queryWrapper = new QueryWrapper();
        try {
            queryWrapper.eq("guid", focAlarm.getGuid() + "_" + focAlarm.getSuggestion().split("\\^")[0]);
        } catch (Exception e) {
            log.info("转换告警异常:" + e.getMessage());
        }
        log.info("guid:" + focAlarm.getGuid());
        MSignal mSignal = mSignalService.getOne(queryWrapper);
        if (mSignal != null) {
            log.info("开始处理配置信号:" +JSONObject.toJSONString(mSignal));
            Date date = new Date();
            date.setTime(focAlarm.getTime()*1000);
            //根据告警类型，判断是活动告警还是历史告警
            if (Objects.equals(1, focAlarm.getMsgType())) {
                log.info("告警开始");
                //生成活动告警
                DActiveAlarm dActiveAlarm = new DActiveAlarm();
                dActiveAlarm.setDeviceid(mSignal.getDeviceid());
                dActiveAlarm.setScid(FocConcat.SCID);
                dActiveAlarm.setSiteid(mSignal.getSiteid());
                dActiveAlarm.setType(mSignal.getType());
                dActiveAlarm.setSignalname(mSignal.getSignalname());
                //取后10位
                dActiveAlarm.setSerialno(focAlarm.getSerialNumber().length()>10?focAlarm.getSerialNumber().substring(focAlarm.getSerialNumber().length()-10):focAlarm.getSerialNumber());
                dActiveAlarm.setAlarmtime(date);
                dActiveAlarm.setAlarmstatus("0");
                dActiveAlarm.setSynno(System.currentTimeMillis());
                dActiveAlarm.setAlarmlevel(focAlarm.getAlarmLevel());
                dActiveAlarm.setAlarmdesc(focAlarm.getContent());
                dActiveAlarm.setAlarmvalue(TypeUtils.castToFloat(focAlarm.getSnapshot()));
                dActiveAlarm.setUploadStatus(0);
                dActiveAlarm.setId(mSignal.getId());
                log.info("保存活动告警成功:" + JSONObject.toJSONString(dActiveAlarm));
                dActiveAlarmService.saveOrUpdate(dActiveAlarm);
                //保存告警后，发送告警，获取通道链接
                //要求的告警登记告警级别大于等于当前告警级别才发送
                if (mSignal.getAlarmlevel() <= focAlarm.getAlarmLevel()) {
                    //给联通发送告警
                       this.sendAlarmCinterface(dActiveAlarm);
                }
            } else if (Objects.equals(2, focAlarm.getMsgType())) {
                log.info("告警结束："+focAlarm.getGuid());
                DAlarmH dAlarmH = new DAlarmH();
                //告警结束，从活动告警中删除
                DActiveAlarm dActiveAlarm = dActiveAlarmService.getOne(new QueryWrapper<DActiveAlarm>().eq("serial_number", focAlarm.getSerialNumber()));
                if(dActiveAlarm!=null){
                    dActiveAlarmService.removeById(dActiveAlarm.getId());
                    dAlarmH.setStarttime(dActiveAlarm.getAlarmtime());
                }else {
                    log.info("该告警序号不存在:"+focAlarm.getSerialNumber());
                    return;
                   // dAlarmH.setStarttime(date);
                }
                //插入一条历史告警
                dAlarmH.setDeviceid(mSignal.getDeviceid());
                dAlarmH.setScid(FocConcat.SCID);
                dAlarmH.setSiteid(mSignal.getSiteid());
                //默认传入DI TODO
                dAlarmH.setType("2");
                dAlarmH.setId(mSignal.getId());
                dAlarmH.setSignalname(mSignal.getSignalname());
                dAlarmH.setSerialno(focAlarm.getSerialNumber().length()>10?focAlarm.getSerialNumber().substring(focAlarm.getSerialNumber().length()-10):focAlarm.getSerialNumber());
                dAlarmH.setEndtime(date);
                dAlarmH.setId(mSignal.getId());
                dAlarmH.setAlarmlevel(focAlarm.getAlarmLevel());
                dAlarmH.setAlarmdesc(focAlarm.getContent());
                dAlarmH.setAlarmvalue(TypeUtils.castToFloat(focAlarm.getSnapshot()));
                log.info("保历史告警成功:" + JSONObject.toJSONString(dAlarmH));
                dAlarmHMapper.insert(dAlarmH);
                //给联通发送告警
                //保存告警后，发送告警，获取通道链接
                //要求的告警登记告警级别大于等于当前告警级别才发送
                if (mSignal.getAlarmlevel() <= focAlarm.getAlarmLevel()) {
                    //给联通发送告警
                     this.sendAlarmCinterface(dAlarmH);
                }
            }else {
                log.info("告警类型错误:"+focAlarm.getMsgType());
            }
            mSignal.setValue(focAlarm.getSnapshot());
            mSignal.setUpdatetime(date);
            mSignalService.updateById(mSignal);
        }else{
            log.info("未找到信号表数据:"+focAlarm.getGuid()+"_"+focAlarm.getSuggestion().split("\\^")[0]);
        }


    }


    @Override
    public void sendAlarmCinterface(DActiveAlarm dActiveAlarm) {
        log.info("发送告警给联通"+JSONObject.toJSONString(dActiveAlarm));
        //通道已建立
        if (LoginHandler.goladChannel != null) {
            //组装发送的消息
            Message message = new Message();
            message.setMessageType(MessageTypeEnum.SEND_ALARM.getValue());
            message.setMessageSerialNo(SendMessageUtils.messageSerialNo);
            ByteBuf buf = Unpooled.buffer();
            //写入告警数量
            buf.writeIntLE(1);
            //写入告警序列号
            byte[] serialnoBytes = SendMessageUtils.padWithSpaces(dActiveAlarm.getSerialno(), AttributeLength.ALARMSERIALNO_LENGTH.getLength());
            //写入监控标识
            byte[] idBytes = SendMessageUtils.padWithSpaces(dActiveAlarm.getId(), AttributeLength.ID_LEN.getLength());
            //写入告警时间
            String date = DateFormatUtils.format(dActiveAlarm.getAlarmtime(), "yyyy-MM-dd HH:mm:ss");
            byte[] timeBytes = SendMessageUtils.padWithSpaces(date, AttributeLength.TIME_LEN.getLength());
            //写入告警描述
            byte[] descBytes = SendMessageUtils.padWithSpaces(dActiveAlarm.getAlarmdesc(), AttributeLength.DES_LENGTH.getLength());
            buf.writeBytes(serialnoBytes);
            buf.writeBytes(idBytes);
            buf.writeBytes(timeBytes);
            //写入告警级别
            buf.writeIntLE(dActiveAlarm.getAlarmlevel());
            //写入告警标志
            if ("1".equals(dActiveAlarm.getAlarmstatus())) {
                buf.writeIntLE(0);
            } else {
                buf.writeIntLE(1);
            }
            //吸入告警触发值
            buf.writeFloatLE(dActiveAlarm.getAlarmvalue());
            buf.writeBytes(descBytes);
            //写入完成后，发送
            message.setBuffer(buf);
            LoginHandler.goladChannel.writeAndFlush(message);
        }
    }

    @Override
    public void sendAlarmCinterface(DAlarmH dAlarmH) {
        //通道已建立
        if (LoginHandler.goladChannel != null) {
            log.info("实时发送告警给联通：" + JSONObject.toJSONString(dAlarmH));
            //组装发送的消息
            Message message = new Message();
            message.setMessageType(MessageTypeEnum.SEND_ALARM.getValue());
            message.setMessageSerialNo(SendMessageUtils.messageSerialNo);
            ByteBuf buf = Unpooled.buffer();
            //写入告警数量
            buf.writeIntLE(1);
            //写入告警序列号
            byte[] serialnoBytes = SendMessageUtils.padWithSpaces(dAlarmH.getSerialno(), AttributeLength.ALARMSERIALNO_LENGTH.getLength());
            //写入监控标识
            byte[] idBytes = SendMessageUtils.padWithSpaces(dAlarmH.getId(), AttributeLength.ID_LEN.getLength());
            //写入告警时间
            String date = DateFormatUtils.format(dAlarmH.getEndtime(), "yyyy-MM-dd HH:mm:ss");
            byte[] timeBytes = SendMessageUtils.padWithSpaces(date, AttributeLength.TIME_LEN.getLength());
            //写入告警描述
            byte[] descBytes = SendMessageUtils.padWithSpaces(dAlarmH.getAlarmdesc(), AttributeLength.DES_LENGTH.getLength());
            buf.writeBytes(serialnoBytes);
            buf.writeBytes(idBytes);
            buf.writeBytes(timeBytes);
            //写入告警级别
            buf.writeIntLE(dAlarmH.getAlarmlevel());
            //写入告警标志，结束
            buf.writeIntLE(1);
            //吸入告警触发值
            buf.writeFloatLE(dAlarmH.getAlarmvalue());
            buf.writeBytes(descBytes);
            //写入完成后，发送
            message.setBuffer(buf);
            LoginHandler.goladChannel.writeAndFlush(message);

        }
    }
}
